package com.yjc.drygoods.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yjc.common.constant.ProductUpStatus;
import com.yjc.common.to.SpuHasStock;
import com.yjc.common.to.SkuReductionTo;
import com.yjc.common.to.SpuBoundTo;
import com.yjc.common.utils.PageUtils;
import com.yjc.common.utils.R;
import com.yjc.drygoods.product.dao.SpuInfoDao;
import com.yjc.drygoods.product.entity.*;
import com.yjc.drygoods.product.feign.CouponFeignService;
import com.yjc.drygoods.product.feign.SearchFeignService;
import com.yjc.drygoods.product.feign.WareFeignService;
import com.yjc.drygoods.product.service.*;
import com.yjc.drygoods.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    CategoryService categoryService;

//    @Autowired
//    BrandService brandService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public void upSkuInfo(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuInfosBySpuId(spuId);

        //1.查询当前sku所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseListForSpus = productAttrValueService.getBaseListForSpu(spuId);
        List<Long> attrList = baseListForSpus.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> allowSearchAttrIds = attrService.getAllowSearchAttr(attrList);
        Set<Long> longs = new HashSet<>(allowSearchAttrIds);
        List<SkuEsModel.Attrs> skuEsModelAttrs = baseListForSpus.stream()
                .filter(item -> {
                    return longs.contains(item.getAttrId());
                }).map(item -> {
                    SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                })
                .collect(Collectors.toList());

        //2.远程调用库存服务，查询是否有库存（返回TRUE或FALSE）
        List<Long> skuIds = skuInfoEntities.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());
        R skuHasStocks = wareFeignService.getSkuWare(skuIds);
        Map<Long, Boolean> hashStockMaps = null;
        if (skuHasStocks.getCode() != 0) {
            log.info("获取库存信息出现异常");
        } else {
            TypeReference<List<SpuHasStock>> typeReference = new TypeReference<List<SpuHasStock>>() {
            };
            List<SpuHasStock> data = skuHasStocks.getData(typeReference);
            hashStockMaps = data.stream()
                    .collect(Collectors.toMap(SpuHasStock::getSpuId, SpuHasStock::getHashStock));
        }
        Map<Long, Boolean> finalHashStockMaps = hashStockMaps;


        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            skuEsModel.setHotScore(0L);
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            //使用完整三级分类链名称，逗号分隔
//            String catelogNamePath = categoryService.findCatelogNamePath(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
//            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
//            skuEsModel.setBrandName(brandEntity.getName());
//            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setAttrs(skuEsModelAttrs);
            Long hashStockSku = skuInfoEntity.getSkuId();
            if (finalHashStockMaps == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalHashStockMaps.get(hashStockSku));
            }
            return skuEsModel;
        }).collect(Collectors.toList());


        //3.调用远程es检索服务,将数据保存进es
        R r = searchFeignService.saveSkuEsModels(skuEsModels);
        if (r.getCode() == 0) {
            this.baseMapper.updatePublishStatus(spuId, ProductUpStatus.UP_SPU.getCode());
        } else {
            log.error("商品上架异常");
        }
    }

    @Transactional
    @Override
    public void downSkuInfo(Long spuId) {
        List<SkuInfoEntity> skuInfos = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> collect = skuInfos.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        R r = searchFeignService.downAllSku(collect);
        if (r.getCode() != 0) {
            throw new RuntimeException("远程检索服务条用异常");
        }
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setId(spuId);
        spuInfoEntity.setPublishStatus(ProductUpStatus.DOWN_SPU.getCode());
        this.updateById(spuInfoEntity);

    }

    @Transactional
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        /**
         *    catelogId: 6,//三级分类id
         *    brandId: 1,//品牌id
         *    status: 0,//商品状态
         *    key: '华为',//检索关键字
         */
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(i -> i.eq("id", key).or().like("spu_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1.保存spu基本信息。`pms_spu_info`
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        CategoryEntity categoryEntity = categoryService.getById(spuInfoEntity.getCatalogId());
        spuInfoEntity.setCatalogName(categoryEntity.getName());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2.保存spu的描述图片。`pms_spu_info_desc`
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", spuSaveVo.getDecript()));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3.保存spu的图片集。`pms_spu_images`
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), spuSaveVo.getImages());

        //4.保存spu的规格信息。`pms_product_attr_value`
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(i -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(i.getAttrId());
            productAttrValueEntity.setAttrName(attrService.getById(i.getAttrId()).getAttrName());
            productAttrValueEntity.setAttrValue(i.getAttrValues());
            productAttrValueEntity.setQuickShow(i.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValue(collect);

        //5.保存当前spu对应的所有sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(i -> {
                //5.1）sku的基本信息。`pms_sku_info`
                String defaultImage = "";
                for (Images t : i.getImages()) {
                    if (t.getDefaultImg() == 1) {
                        defaultImage = t.getImgUrl();
                        break;
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(i, skuInfoEntity);
                skuInfoEntity.setReducedPrice(i.getPrice());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0.0);
//                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setCatalogName(spuInfoEntity.getCatalogName());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                List<Attr> attr1 = i.getAttr();
                Map<String, String> collect1 = attr1.stream().collect(Collectors.toMap(Attr::getAttrName, Attr::getAttrValue));
                String weightValue = collect1.get("重量");
                skuInfoEntity.setWeight(weightValue.equals("1斤") ? 1 : 0.4);
                log.info("weight:{}", weightValue);
                log.info("flage:{}", weightValue.equals("1斤"));
//                int j = 1 / 0;
                skuInfoService.saveSkuInfos(skuInfoEntity);

                //5.2）sku的图片信息。`pms_sku_images`
                List<Images> images = i.getImages();
                List<SkuImagesEntity> skuImages = images.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    BeanUtils.copyProperties(image, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).filter(ima -> {
                    //没有图片路径信息不用保存
                    return !StringUtils.isEmpty(ima.getImgUrl());
                }).collect((Collectors.toList()));
                skuImagesService.saveBatchSkuImages(skuImages);
                //5.3）sku的销售属性信息。`pms_sku_sale_attr_value`
                List<Attr> attrs = i.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatchSkuSaleAttrValues(skuSaleAttrValueEntities);

                //5.4）sku的优惠、满减等信息。drygoods_sms->`sms_sku_ladder`\`sms_sku_full_reduction`\`sms_member_price`

                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(i, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("远程保存优惠、满减等信息，失败");
                    }
                }
            });
        }


        //6.保存spu的积分信息。drygoods_sms->`sms_spu_bounds`
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        Bounds bounds = spuSaveVo.getBounds();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu的积分信息，失败");
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }


}